import type {App} from 'vue'
import {createI18n} from 'vue-i18n'
import type {I18n} from 'vue-i18n'
import {useConfig} from '../stores/config'

/*
 * 引入 element-plus 的中英文语言包
 */
import elementZhcnLocale from 'element-plus/lib/locale/lang/zh-cn'
import elementEnLocale from 'element-plus/lib/locale/lang/en'

export let i18n: I18n<{[p: string]: any}, unknown, unknown, false>

interface assignLocale {
    [key: string]: any
}

// 准备要合并的语言包
const assignLocale: assignLocale = {
    'zh-cn': [elementZhcnLocale],
    en: [elementEnLocale],
}

export async function loadLang(app: App) {
    const config = useConfig()
    const locale = config.lang.defaultLang

    // 加载框架语言包
    const lang = await import(`../lang/${locale}.ts`)
    const message = lang.default ?? {}
    const messages = {
        [locale]: {
            ...message,
        },
    }
    // 合并语言包
    Object.assign(messages[locale], ...assignLocale[locale])
    i18n = createI18n({
        locale: locale,
        legacy: false,
        globalInjection: true,
        fallbackLocale: config.lang.fallbackLang,
        messages,
    })

    app.use(i18n)
    return i18n
}

export function editDefaultLang(lang: string): void {
    const config = useConfig()
    config.setLang(lang)
    location.reload()
}
